package com.cn.shiro.demo.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    // 创建请求过滤器 3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // shiro过滤规则
        /*  anon:无需认证就可以访问
            authc:必须认证了才能让问
            user:必须拥有记住我功能才能用
            perms:拥有对某个资源的权限才能访问;
            role:拥有某个角色权限才能访问
            (支持通配符)
        */
        // 拦截
        Map<String,String> fiterMap = new LinkedHashMap<>();
       /*
           认证了才能访问update资源
        fiterMap.put("/user/update","authc");
       */
        // 资源权限
        fiterMap.put("/user/add","perms[user:add]");
        fiterMap.put("/user/update","perms[user:update]");
        // 添加 shiro过滤规则
        shiroFilterFactoryBean.setFilterChainDefinitionMap(fiterMap);
        // 如果拦截跳转登录请求
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        // 如果授权限制的页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noauth");
        return shiroFilterFactoryBean;
    }
    // 创建安全管理器 2
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }
    // 创建自定义Realm 1
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
    // shiro方言  整合thymeleaf支持shiro标签
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}
